package com.chemical.search.view.manage;

import java.io.File;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.chemical.search.dto.QueryChemDTO;
import com.chemical.search.model.AdditionalAttribute;
import com.chemical.search.model.BaseAttribute;
import com.chemical.search.service.IAdditionalAttributeService;
import com.chemical.search.service.IBaseAttributeService;
import com.chemical.search.util.common.EncodeUtil;
import com.chemical.search.util.page.Condition;
import com.chemical.search.util.page.Page;
import com.chemical.search.util.page.PageUtil;
import com.chemical.search.util.query.PropertyFilter;
import com.chemical.search.view.BaseController;

/**
 *@className:ChemController.java
 *@classDescription:
 *@author:MChen
 *@createTime:2012-6-11
 */
@Controller
@RequestMapping("/manage/chem")
public class ChemController extends BaseController{
	
	Page<BaseAttribute> page = new Page<BaseAttribute>(10);
	@Autowired
	protected IBaseAttributeService baseAttributeService ;
	@Autowired
	protected IAdditionalAttributeService additionalAttributeService ;
	
	@RequestMapping(value={"/list",""})
	public String listDownInfo(QueryChemDTO chemDTO,Model model,HttpServletRequest request){
		//获取查询条件
		String name_en = null;
		String name_cn = null;
		String molecular_formula = null;
		String cas_rn = null;
		try {
			name_en = chemDTO.getName_en().trim();
			name_cn = chemDTO.getName_cn().trim();
			molecular_formula = chemDTO.getMolecular_formula().trim();
			cas_rn = chemDTO.getCas_rn().trim();
		} catch (Exception e) {}
//		String startDate = chemDTO.getStartDate();
//		String endDate = chemDTO.getEndDate();
		String order = chemDTO.getOrder();
		int pageNo = chemDTO.getPageNo();
		
		//查询条件
		PropertyFilter n_en = new PropertyFilter("name_en:LIKE_S", name_en);
		PropertyFilter n_cn = new PropertyFilter("name_cn:LIKE_S", name_cn);
		PropertyFilter m_for = new PropertyFilter("molecular_formula:LIKE_S",molecular_formula);
		PropertyFilter cas = new PropertyFilter("cas_rn:LIKE_S",cas_rn);
//		PropertyFilter startPf = new PropertyFilter("inputTime:GT_D",startDate);
//		PropertyFilter endPf = new PropertyFilter("inputTime:LT_D", endDate);
		List<PropertyFilter> pfList = new ArrayList<PropertyFilter>();
		pfList.add(n_en);
		pfList.add(n_cn);
		pfList.add(m_for);
		pfList.add(cas);
//		pfList.add(startPf);
//		pfList.add(endPf);
		//设置跳转页面
		StringBuffer forwordName = new StringBuffer(this.getRoot(request)
				+ "/manage/chem/list.do");
		//获取分页跳转页面
		List<Condition> fragmentList=new ArrayList<Condition>();
		fragmentList.add(new Condition("name_en",EncodeUtil.urlEncode(name_en),"匹配'"+name_en+"'"));
		fragmentList.add(new Condition("name_cn",EncodeUtil.urlEncode(name_cn),"匹配'"+name_cn+"'"));
		fragmentList.add(new Condition("molecular_formula",EncodeUtil.urlEncode(molecular_formula),"匹配'"+molecular_formula+"'"));
		fragmentList.add(new Condition("cas_rn",EncodeUtil.urlEncode(cas_rn),"匹配'"+cas_rn+"'"));
//		fragmentList.add(new Condition("startDate", startDate, "大于" + startDate));
//		fragmentList.add(new Condition("endDate", endDate, "小于" + endDate));
		
		String forwarCondition=PageUtil.getForwardCondition(fragmentList);
		forwordName.append(forwarCondition);
		// 获取排序跳转页面
		String orderCondition = PageUtil.getOrderCondition(fragmentList);
		model.addAttribute("order", orderCondition);
		// 获取过滤查询集合
		List<Condition> filterList = PageUtil.getFilterConditions(fragmentList);
		model.addAttribute("filterList", filterList);
	    // 初始化page属性值--默认id排序
		if (null == order) {
			page.setOrder("id");
		} else {
			page.setOrder(order);
		}
		page.setPageNo(pageNo);
		//查询所有的歌曲信息,并放入会话
		page = this.baseAttributeService.searchAttribute(page,pfList);
		model.addAttribute("chemInfoList", page.getResult());
		
		//生成分页标签
		page.setForwordName(forwordName.toString());
		String tag=PageUtil.getTag(page);
		model.addAttribute("tag", tag);
		//索引号
		model.addAttribute("index", page.getFirst());
		
		//设置页面搜索初始值
		model.addAttribute("name_en", name_en);
		model.addAttribute("name_cn", name_cn);
		model.addAttribute("molecular_formula", molecular_formula);
		model.addAttribute("cas_rn", cas_rn);
//		model.addAttribute("startDate", startDate);
//		model.addAttribute("endDate", endDate);
		String currentPage=request.getRequestURI().toString()+forwarCondition+page.getPageNo();
		request.getSession().setAttribute("currentPage",currentPage );
		
		return  "manage/chem/chemManage.jsp";
	}
	
	@RequestMapping(value = "/addChem")
	public String addChem(HttpServletRequest request,Model model){
		return "manage/chem/addchem.jsp";
	}
	
	/**
	 * 化合物信息录入
	 * @param model
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="/add")
	public String addInfo(@RequestParam(value = "picture", required = false) MultipartFile file1,
						  @RequestParam(value = "mass_spectrum_file", required = false) MultipartFile file2,
						  @RequestParam(value = "infrared_file", required = false) MultipartFile file3,
						  @RequestParam(value = "nuclear_file", required = false) MultipartFile file4,
						  BaseAttribute att,AdditionalAttribute aattr,HttpServletRequest request,HttpServletResponse response){
		if(StringUtils.isBlank(att.getCas_rn()) || 
		   StringUtils.isBlank(att.getName_cn()) ||
		   StringUtils.isBlank(att.getName_en()) ||
		   StringUtils.isBlank(att.getMolecular_formula())
		){
			response.setContentType("text/html; charset=utf-8");
			PrintWriter out = null;
			try {
				out = response.getWriter();
				// 输出业务层返回的json
				out.print("<script>alert('您需要先输入化合物的基本信息');window.location='"+request.getContextPath()+"/manage/chem/addchem.jsp';</script>");
				out.flush();
				out.close();
//				response.sendRedirect(request.getContextPath()+"/manage/chem/add.do");
//				request.getRequestDispatcher("/manage/chem/add.do").forward(request, response);
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				if (null != out) {
					out.close();
				}
			}
		}
		else{
			try{
				 Random random1 = new Random(100);
		        String molpath = request.getSession().getServletContext().getRealPath("common/molPNG");
		        String syntheticmethodpath = request.getSession().getServletContext().getRealPath("common/mass_spectrum_file");
		        String massspectrumpath = request.getSession().getServletContext().getRealPath("common/infrared_file");
		        String infrarepath = request.getSession().getServletContext().getRealPath("common/nuclear_file");
		        String fileName1 = file1.getOriginalFilename();
		        String fileName2 = file2.getOriginalFilename();
		        String fileName3 = file3.getOriginalFilename();
		        String fileName4 = file4.getOriginalFilename();
		       
		        if(!StringUtils.isBlank(fileName1)){
		        	fileName1 = new Date().getTime()+"--"+random1.nextInt()+".jpg";
		        }
		        if(!StringUtils.isBlank(fileName2)){
		        	 fileName2 = new Date().getTime()+"--"+random1.nextInt()+".jpg";
		        }
		        if(!StringUtils.isBlank(fileName3)){
		        	fileName3 = new Date().getTime()+"--"+random1.nextInt()+".jpg";
		        }
		        if(!StringUtils.isBlank(fileName4)){
		        	 fileName4 = new Date().getTime()+"--"+random1.nextInt()+".jpg";
		        }
//		        String fileName = new Date().getTime()+".jpg";
		        File targetFile1 = new File(molpath, fileName1);
		        if(!targetFile1.exists()){
		            targetFile1.mkdirs();
		        }
		        File targetFile2 = new File(syntheticmethodpath, fileName2);
		        if(!targetFile2.exists()){
		            targetFile2.mkdirs();
		        }
		        File targetFile3 = new File(massspectrumpath, fileName3);
		        if(!targetFile3.exists()){
		            targetFile3.mkdirs();
		        }
		        File targetFile4 = new File(infrarepath, fileName4);
		        if(!targetFile4.exists()){
		            targetFile4.mkdirs();
		        }

		        //保存
		        try {
		            file1.transferTo(targetFile1);
		            file2.transferTo(targetFile2);
		            file3.transferTo(targetFile3);
		            file4.transferTo(targetFile4);
		        } catch (Exception e) {
		            e.printStackTrace();
		        }
		        att.setPicture_Name("molPNG"+File.separator+fileName1);
				boolean boo = this.baseAttributeService.save(att);
				if(boo == true){
					int scr = att.getScr();
					aattr.setBaseattribute(att);
					aattr.setMass_spectrum(fileName2);
					aattr.setInfrared(fileName3);
					aattr.setNuclear(fileName4);
					boo = this.additionalAttributeService.save(aattr);
					return "success.jsp";
				}
			}
			catch(Exception e){
				e.printStackTrace();
		 }
		}
		return null;
	}
}
